$(function (){
    var $table = $('#datatable');
    var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
        ajax : function(data, callback, settings) {//ajax配置为function,手动调用异步查询
        	var param = fitParams.getQueryCondition(data);
            $.ajax({
                    type: "POST",
                    url: "/XYL/power/roleList",
                    cache : false,  //禁用缓存
                    data: param,    //传入已封装的参数
                    dataType: "json",
                    success: function(result) {
                        //setTimeout仅为测试延迟效果
                        setTimeout(function(){
                            //异常判断与处理
                            if (result.errorCode) {
                                $.messager.alert('提示信息', '查询失败。错误码：'+result.errorCode, 'warning');
                                return;
                            }
 
                            var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = result.recordsTotal;
                            returnData.recordsFiltered = result.recordsTotal;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.data;
                            
                            //console.debug(data);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        },200);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('提示信息', '查询失败', 'warning');
                       // $wrapper.spinModal(false);
                    }
                });
        },
        scrollX: "100%",
        columns: [
            CONSTANT.DATA_TABLES.COLUMN.CHECKBOX,
            {
            	className : "ellipsis",
                data: "roleId",
                visible:false,
            },
            {
            	className : "ellipsis",
                data: "roleCode",
                render : CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
                width : "100px",
            },
            {
            	className : "ellipsis",
                data: "roleName",
                render : CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
                width : "100px",
            },
            {
            	className : "ellipsis",
            	data: "roleDescription",
            	render : CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
            	width : "100px",
            }
        ],
        "createdRow": function ( row, data, index ) {
        	//$('td', row).eq(4).css("display","none");
        },
        "drawCallback": function( settings ) {
            $("tbody tr",$table).eq(0).click();
        }
    })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象
   
    
    //行点击事件
    $("tbody",$table).on("click","tr",function(event) {
        //获取该行对应的数据
        var item = _table.row($(this).closest('tr')).data();
        //console.debug(item);
    });
 
    $table.on("change",":checkbox",function() {
        if ($(this).is("[name='cb-check-all']")) {
            //全选
            $(":checkbox",$table).prop("checked",$(this).prop("checked"));
        }else{
            //一般复选
            var checkbox = $("tbody :checkbox",$table);
            $(":checkbox[name='cb-check-all']",$table).prop('checked', checkbox.length == checkbox.filter(':checked').length);
        }
    }).on("click",".td-checkbox",function(event) {
        //点击单元格即点击复选框
        !$(event.target).is(":checkbox") && $(":checkbox",this).trigger("click");
    });
    //模糊查询事件
    $("#btn-search").click(function (){
    	_table.draw();
    });
  //添加事件
    $("#btn-add").click(function (){
    	$('#editForm').form('clear');
    	$('#edit').window({
            width:400,
            height:400,
            modal:true,
            minimizable:false,
            inline:false
        });
    });
    //编辑事件
    $("#btn-edit").click(function (){
    	var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item);
        });
    	$('#editForm').form('clear');
        if(arrItemId.length==1){ 
        	$('#editForm').form('load', '/XYL/power/getrole?id='+arrItemId[0].roleId);
        }else{
        	$.messager.alert('提示信息', '请选择 一条信息', 'warning');
        	return;
        }
    	$('#edit').window({
    		width:"400",
    		height:"400",
    		modal:true,
    		minimizable:false,
    		inline:false
    	});
    });
  //提交
    $('#editForm').form({
    	url:"/XYL/power/saveaddupdaterole",
    	onSubmit:function(){
    		return $(this).form('validate');
    	},
    	success: function (result) { 
    		if(result.status=="fail"){
    			$.messager.alert("提示信息","数据添加失败！","error");
    		}
    		$('#edit').window('close'); 
    		_table.draw();
    	}
    });
    $('#editForm').submit();
    //删除事件（支持批量删除）
    $("#btn-del").click(function (){
    	var arrItemId = [];
        $("tbody :checkbox:checked",$table).each(function(i) {
        	var item = _table.row($(this).closest('tr')).data();
        	arrItemId.push(item.roleId);
        });
		CONSTANT.FUNCTION.deleteItemNoId(arrItemId,"/XYL/power/deleterole",_table);
    });
    $("#btn-view-user").click(function (){
    	var selectTtem=CONSTANT.FUNCTION.tableselectone($table,_table);
    	CONSTANT.FUNCTION.popupdialogfun("userId,userName,truename","/XYL/user/userListByroleId?roleId="+selectTtem.roleId,"popuptable_user");
    });
    //编辑权限
    
    $("#btn-add-resource").click(function(){
    	var selectRoleItem=CONSTANT.FUNCTION.tableselectone($table,_table);
    	$('#add_resource').window({
    		width:"400",
    		height:"500",
    		modal:true,
    		minimizable:false,
    		inline:false
    	});
    	 $("#tree").tree({
	    	url:'/XYL/power/list?roleId='+selectRoleItem.roleId,
	    	method:'get',
	    	animate:true,
	    	checkbox:true
    	  });
    	 
    	
    });
    
    $('#add_resource_btn').click(function(){
    	var  checknNodes=$('#tree').tree("getChecked");//所有选中节点 
    	var selectRoleItem=CONSTANT.FUNCTION.tableselectone($table,_table);
    	var resourceIdArry=[];
    	for(var i=0;i<checknNodes.length;i++){
    		resourceIdArry.push(checknNodes[i].id);
    	}
    	$.ajax({
	    	type: "POST",
	    	url: "/XYL/power/saveroleresource",
	    	data:{
	    		roleId:selectRoleItem.roleId,
	    		resourceIdStr:resourceIdArry.join(",")
	    	},
	    	cache : false,  //禁用缓存
	        dataType: "json",
	    	success: function(res){
	    		if(res.status=="success"){
	    			$.messager.alert("提示信息","保存成功！","success");
	    			$('#add_resource').window('close');
	    		}else{
	    			$.messager.alert("提示信息","保存失败！","success");
	    		}
	    		resourceIdArry=[];
	        }
    	});
    });
    
});


//组装参数
var fitParams = {
		currentItem : null,
		getQueryCondition : function(data) {
			var param = {};
			//组装排序参数
			if (data.order&&data.order.length&&data.order[0]) {
				switch (data.order[0].column) {
				case 1:
					param.orderColumn = "roleId";
					break;
				case 2:
					param.orderColumn = "roleCode";
					break;
				case 3:
					param.orderColumn = "roleName";
					break;
				case 4:
					param.orderColumn = "roleDescription";
					break;
				default:
					param.orderColumn = "roleId";
					break;
				}
				param.orderDir = data.order[0].dir;
			}
			//组装查询参数
			param.fuzzy = $("#fuzzy-search").val();
			if (param.fuzzy=="") {
				param.fuzzySearch = false;
			}else{
				param.fuzzySearch = true;
			}
			//组装分页参数
			param.currentItem = data.start;
			param.pageSize = data.length;
			param.draw = data.draw;
			return param;
		}
		
	};
 


